print 'Content-type: text/plain'
print

import sys
import urllib2
import cgi

appId = ''
uri = 'http://api.microsofttranslator.com/V2/Ajax.svc/'
form = cgi.FieldStorage( )

action = form.getvalue( 'action' )
text = urllib2.quote( form.getvalue( 'text' ) )

if action != 'speak':
  sys.exit( 1 )

detect_uri = '%sDetect?appId=%s&text=%s' % ( uri, appId, text )
language = ''
for line in urllib2.urlopen( detect_uri ):
  language += line
language = language.strip( )

format = 'audio/wav'
speak_uri = '%sSpeak?appId=%s&text=%s&language=%s&format=%s'% ( uri, appId, text, language, format )

for line in urllib2.urlopen( speak_uri ):
  print line

